package com.zjy.pgcms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjy.pgcms.common.BaseResponse;
import com.zjy.pgcms.common.ErrorCode;
import com.zjy.pgcms.common.Result;
import com.zjy.pgcms.common.vo.UserInfoVO;
import com.zjy.pgcms.dto.user.*;
import com.zjy.pgcms.entity.User;
import com.zjy.pgcms.exception.BusinessException;
import com.zjy.pgcms.service.UserService;
import com.zjy.pgcms.util.EncryptUtil;
import com.zjy.pgcms.util.ValidationUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author 音音音
 */
@RestController
public class UserController {
    @Resource
    private UserService userService;

    private boolean status = true;

    @RequestMapping("user/get/list")
    public Object list(){
        return userService.list();
    }

    @PostMapping("user/register")
    public BaseResponse userRegister(@RequestBody UserRegisterDTO dto){
        Boolean isBadRegParam = dto.paramsValidation();//参数校验
        if (isBadRegParam){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = dto.getUsername();
        String password = dto.getPassword();
        password = EncryptUtil.encryptString(password);//对密码进行加密
        QueryWrapper queryWrapper = new QueryWrapper();//检查用户是否存在
        queryWrapper.eq("username", username);
        long selectUserCount = userService.count(queryWrapper);
        if (selectUserCount > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户已存在");
        }
        Boolean isSaveSuccess = userService.save(new User(username, password));//存入数据库
        if (isSaveSuccess){
            return Result.success();
        }else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    @PostMapping("user/login")
    public BaseResponse userLogin(@RequestBody UserLoginDTO dto, HttpServletRequest request, HttpServletResponse response){
        //1.接收参数，验证参数合法性
        Boolean isBadLoginParam = dto.paramsValidation();
        if (isBadLoginParam){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = dto.getUsername();
        String password = dto.getPassword();
        //2.对密码进行加密
        password = EncryptUtil.encryptString(password);

        //3.从数据库中查询数据出user对象
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        //4.如果查询出一条数据，存入session
        HttpSession session = request.getSession();
        user.setPassword("");
        session.setAttribute("user",user);
        session.setMaxInactiveInterval(60*60*24*30);

        //5.设置sessionId过期时间
        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60*60*24*30);
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        response.addCookie(cookie);
        return Result.success();
    }

    @GetMapping("get/login/user")
    public BaseResponse<UserInfoVO> getLoginUser(HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        return Result.success(new UserInfoVO(user));
    }

    @PostMapping("user/update")
    public BaseResponse updateUser(HttpServletRequest request, UserUpdateDTO dto){
        if (!ValidationUtil.hasLoginUser(request.getSession())){
            throw new BusinessException(ErrorCode.NO_LOGIN);
        }
        Boolean isBadParam = dto.paramsValidation();
        if (isBadParam){
           throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User userSession = (User) request.getSession().getAttribute("user");
        String name = dto.getName();
        Byte gender = dto.getGender();
        String phone = dto.getPhone();
        String email = dto.getEmail();
        Long userId = userSession.getId();
        MultipartFile file = dto.getFile();
        User user = new User(userId,name,gender,phone,email);
        if (!dto.getFile().isEmpty()){
            String filePathNet = userService.saveAvatar(file, userId);
            user.setAvatarUrl(filePathNet);
        }
        userService.updateById(user);
        return Result.success();
    }

    @PostMapping("/query/user")
    public BaseResponse queryUser(@RequestBody UserQueryDTO dto){
        QueryWrapper queryWrapper = userService.getQueryWrapper(dto);
        List list = userService.list(queryWrapper);
        return Result.success(list);
    }

    @PostMapping("/query/user/page")
    public BaseResponse queryUserBypage(@RequestBody UserQueryPage userQueryPage){
        List<User> list = userService.queryUserByPage(userQueryPage);
        System.out.println(list);

        return Result.success(list);
    }

    @PostMapping("/query/user/count")
    public BaseResponse queryUserCountBypage(@RequestBody UserQueryPage userQueryPage){
        long count = userService.count(userQueryPage);

        return Result.success(count);
    }

    @GetMapping("/user/auth/admin")
    public BaseResponse auth(HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        if (user == null){
            return Result.error(ErrorCode.NO_LOGIN);
        }else {
            if (user.getId().toString().equals("1751969267020357634")){
                return Result.success(true);
            }
        }
        return Result.error(ErrorCode.PARAMS_ERROR);
    }


    @DeleteMapping("/user/delete/{id}")
    public BaseResponse deleteUser(@PathVariable long id){
        boolean success = userService.removeById(id);
        if (success){
            System.out.println("删除成功"+id);
            return Result.success();
        }else {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
    }

    @GetMapping("/user/status")
    public BaseResponse getStatus(){
        return Result.success(this.status);
    }

    @GetMapping("/user/set/{status}")
    public BaseResponse setStatus(@PathVariable("status") boolean status){
        this.status = status;
        return Result.success();
    }




}
